package edu.yang.dbutils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * 行处理器工具类 - 将一条记录转换为 Array、Map、Bean 等
 * @author yang
 * @date 2024-05-11
 */
public class RowProcessor {

    /**
     * 将结果集转换为数组
     * @param rs
     * @return
     */
    public static Object[] toArray(ResultSet rs) throws SQLException {
        //初始化数组
        Object[] result = new Object[rs.getMetaData().getColumnCount()];
        for (int i = 0; i < result.length; i++) {
            result[i] = rs.getObject(i + 1);
        }
        return result;
    }

    /**
     * 根据列下标查询数据
     * @param rs
     * @param columnIndex
     * @return
     */
    public static Object toValue(ResultSet rs, Integer columnIndex) throws SQLException{
        return rs.getObject(columnIndex);
    }

    /**
     * 根据列名查询数据
     * @param rs
     * @param columnName
     * @return
     * @throws SQLException
     */
    public static Object toValue(ResultSet rs, String columnName) throws SQLException{
        return rs.getObject(columnName);
    }
    public static Map<String ,Object> toMap(ResultSet rs) throws SQLException {
        //初始化map对象
        Map<String, Object> map = new HashMap<>();
        //循环赋值
        for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++){
            map.put(rs.getMetaData().getColumnLabel(i), rs.getObject(i));
        }
        return map;
    }

    public static<T> T toBean(ResultSet rs, Class<T> beanClass) throws SQLException{
        return BeanProcessor.createBean(rs, beanClass);
    }
}
